package com.nis.bcreceiver;

import android.app.Activity;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends Activity implements View.OnClickListener {

    public static final String TAG = "BCReceiver";
//    private LinearLayout rootLayout;
    private Button accesscBt;
    private Button accesscStartNo;
//    private Button ClearViews;
    private PushMessCache pushIns;
    private Intent upservice;
    public static MainActivity activity = null;
//	private static HttpReq req = new HttpReq();
    EditText ed_1,ed_2,ed_3,ed_4,ed_5,ed_6,ed_7,ed_8;
    static EditText ed_url;
    static EditText[] eds;
    //指示线
    TextView tv_one,tv_two;
    View view_one,view_two;
    TextView[] textviews;
    View[] views;
    //指示线end
    LinearLayout ll_more_params;
    //信息展示
    RelativeLayout rl_show;
    Button btn_upload,btn_clear;
    ListView listView;
    static MyAdapter mAdapter;
    //展示
//    新方案
    Intent mService;
    //时间间隔
    EditText ed_clear_time;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity=this;
        activity = this;
        pushIns = new PushMessCache();
        setContentView(R.layout.activity_main);
        initview();
        upservice = new Intent(this, NeNotificationService.class);

//        rootLayout = (LinearLayout) findViewById(R.id.root_layout);
        accesscBt = (Button) findViewById(R.id.buttonAssesc);
        accesscBt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
//                startActivityForResult(intent, 0);
                if (!isNotificationListenerEnabled(MainActivity.this)) {
                    openNotificationListenSettings();
                }else{
                    Toast.makeText(MainActivity.this,"权限已经开启",Toast.LENGTH_SHORT).show();
                }
            }
        });
        if (!isNotificationListenerEnabled(MainActivity.this)) {
            openNotificationListenSettings();
        }else{
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendBroadcast(new Intent(MyReceiver.ReceiverKey));
                }
            }, 1000);
        }
        mService = new Intent(this, WeChatNotificationListenerService.class);
//        findViewById(R.id.btn_clear_all).setOnClickListener(this);
        //启动倒计时
        timeCount = new TimeCount(120000, 1000);
        timeCount.start();
    }
    //初始化view
    public void initview(){
        ed_clear_time=findViewById(R.id.ed_clear_time);
        rl_show=findViewById(R.id.rl_show);
        btn_upload=findViewById(R.id.btn_upload);
        btn_clear=findViewById(R.id.btn_clear);
        btn_upload.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        listView=findViewById(R.id.listView);
        mAdapter=new MyAdapter(this);
        listView.setAdapter(mAdapter);
        ll_more_params=findViewById(R.id.ll_more_params);
        ed_url=findViewById(R.id.ed_url);
        ed_1=findViewById(R.id.ed_1);
        ed_2=findViewById(R.id.ed_2);
        ed_3=findViewById(R.id.ed_3);
        ed_4=findViewById(R.id.ed_4);
        ed_5=findViewById(R.id.ed_5);
        ed_6=findViewById(R.id.ed_6);
        ed_7=findViewById(R.id.ed_7);
        ed_8=findViewById(R.id.ed_8);
        eds=new EditText[]{ed_1,ed_2,ed_3,ed_4,ed_5,ed_6,ed_7,ed_8};
        for (int i = 0; i < eds.length; i++) {
            String edContentSP= (String) SPUtils.get(this,"ed"+i,"");
            if (edContentSP==null||"".equals(edContentSP)) {
                eds[i].setText(""+(i+1));
            }else{
                eds[i].setText(""+edContentSP);
            }
        }
        ed_url.setText(""+SPUtils.get(this,"ed_url",""));
        tv_one=findViewById(R.id.tv_one);
        tv_two=findViewById(R.id.tv_two);
        view_one=findViewById(R.id.view_first);
        view_two=findViewById(R.id.view_second);
        textviews=new TextView[]{tv_one,tv_two};
        views=new View[]{view_one,view_two};
        tv_one.setOnClickListener(this);
        tv_two.setOnClickListener(this);
        views[0].setSelected(true);
        ed_clear_time.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            //改变发送广播的时间
                if (timeCount != null) {
                    timeCount.cancel();
                }
                int timeValue = 120000;
                if (util.isNotEmpty(ed_clear_time.getText().toString())) {
                    timeValue = Integer.valueOf(ed_clear_time.getText().toString()) * 1000;
                }
                timeCount = new TimeCount(timeValue, 1000);
                timeCount.start();
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
//        updateServiceStatus(true);
        startService(mService);
//        if (isNotificationListenerEnabled(MainActivity.this)) {
//            if (isgoSetting) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        sendBroadcast(new Intent(MyReceiver.ReceiverKey));
//                    }
//                }, 1000);
//            }
//        }
    }

    private void updateServiceStatus(boolean start) {
        boolean bRunning = util.isServiceRunning(this, "com.nis.bcreceiver.NeNotificationService");

        if (start && !bRunning) {
            this.startService(upservice);
        } else if (!start && bRunning) {
            this.stopService(upservice);
        }
        bRunning = util.isServiceRunning(this, "com.nis.bcreceiver.NeNotificationService");
//        accesscStartNo.setText(bRunning ? "关闭监听" : "开启监听");
        Toast.makeText(this, bRunning ? "开启监听成功" : "关闭监听成功", Toast.LENGTH_SHORT).show();
        AppLog.i("updateServiceStatus ctrl[ " + start + "] result running:" + bRunning);

    }

    private NotifyDataReceiver receiver = null;

    //数据上传
    public static void upData(final String upMsg){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String[] strings= upMsg.split("##");
                Map<String, String> params = new HashMap<>();
                for (int i = 0; i < eds.length; i++) {
                    if (eds[i].getText().toString().trim()!=null&&!"".equals(eds[i].getText().toString().trim())) {
                        params.put("canshu"+(i+1),eds[i].getText().toString().trim());
                    }
                }
                int currentParamsize=params.size();
                for (int i = 0; i < strings.length; i++) {
                    params.put("canshu"+(i+1+currentParamsize),strings[i]);
                }
                try {
                    HttpUse.postReq(ed_url.getText().toString().trim(),params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void notifyReceive(final String packageName, final Notification notification) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
// 当 API > 18 时，使用 extras 获取通知的详细信息
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    Bundle extras = notification.extras;
                    if (extras != null) {
                        // 获取通知标题
                        String title = extras.getString(Notification.EXTRA_TITLE, "");
                        // 获取通知内容
                        String content = extras.getString(Notification.EXTRA_TEXT, "");

                        String strGetMsg = "" + packageName;
                        strGetMsg += ("##" + title + " " + content);
                        strGetMsg += ("##" + util.getDateByTimeStamp(notification.when + ""));
                        Log.e("after", "消息  一" + notification.tickerText + " extra方式" + title + "  " + content);
                        List<MsgBean> dataList = new ArrayList<>();
                        dataList.add(new MsgBean(util.getDateByTimeStamp(notification.when + ""), "" + packageName, title + " " + content));
                        mAdapter.setData(dataList, false);
                        upData(strGetMsg);
                    }
                }
            }
        });
    }
    public void notifyReceive_show(final String packageName, final Notification notification) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    Bundle extras = notification.extras;
                    if (extras != null) {
                        // 获取通知标题
                        String title = extras.getString(Notification.EXTRA_TITLE, "");
                        // 获取通知内容
                        String content = extras.getString(Notification.EXTRA_TEXT, "");

                        List<MsgBean> dataList = new ArrayList<>();
                        dataList.add(new MsgBean(util.getDateByTimeStamp(notification.when + ""), "" + packageName, title + " " + content));
                        mAdapter.setData(dataList, false);
                    }
                }
            }
        });
    }
//就是把获取到的信息+获取的时间（当前手机时间）记录下来，然后显示成一个列表，
// 后面加一个重新提交此条消息跟批量提交此列表的信息，上传的时候要加上这个获取的时间，还能删除这个列表

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_one:
                topGuid(0);
                break;
            case R.id.tv_two:
                topGuid(1);
                break;
            case R.id.btn_clear:
                mAdapter.setData(null, true);
                break;
            case R.id.btn_upload:
//                strGetMsg
                List<MsgBean> dataList=mAdapter.getDataList();
                if (dataList!=null&&dataList.size()!=0) {
                    String strGetMsg=util.getDoubleJsonArray(dataList);
                    upData(strGetMsg);
                }else{
                    Toast.makeText(this, "没有需要上传内容", Toast.LENGTH_SHORT).show();
                }
                break;
//            case R.id.btn_clear_all:
//                sendBroadcast(new Intent(MyClearReceiver.ClearKey));
//                break;
        }
    }

    public class NotifyDataReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // AppLog.i("Receiver got msg in onReceive()...");

            Parcelable notifyParcelable = intent.getParcelableExtra("NotifyData");
            String packageName = intent.getStringExtra("packageName");
            if (notifyParcelable != null) {
                Notification notification = (Notification) notifyParcelable;
            }

        }
    }

    @Override
    protected void onDestroy() {
        // if(receiver != null)
        // this.unregisterReceiver(receiver);
        super.onDestroy();
        updateServiceStatus(false);

        for (int i = 0; i < eds.length; i++) {
            if (util.isNotEmpty(eds[i].getText().toString().trim())) {
                SPUtils.put(this,"ed"+i,eds[i].getText().toString().trim());
            }else{
                SPUtils.put(this,"ed"+i,"");
            }
        }
        if (util.isNotEmpty(ed_url.getText().toString().trim())) {
            SPUtils.put(this,"ed_url",ed_url.getText().toString().trim());
        }else{
            SPUtils.put(this,"ed_url","");
        }
        if (timeCount != null) {
            timeCount.cancel();
        }
    }
    //头部转化色
    public void topGuid(int position) {
        for (int i = 0; i < views.length; i++) {
            if (i == position) {
                views[i].setSelected(true);
                textviews[i].setTextColor(getResources().getColor(R.color.color_e74b3c));
            } else {
                views[i].setSelected(false);
                textviews[i].setTextColor(getResources().getColor(R.color.color_333333));
            }
        }
        if (position == 0) {
            ll_more_params.setVisibility(View.VISIBLE);
            rl_show.setVisibility(View.GONE);
        } else {
            ll_more_params.setVisibility(View.GONE);
            rl_show.setVisibility(View.VISIBLE);
        }
    }

    public void openNotificationListenSettings() {
        try {
            Intent intent;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
            } else {
                intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            }
            startActivity(intent);
            isgoSetting=true;
        } catch (Exception e) {
            isgoSetting=false;
            e.printStackTrace();
        }
    }
    boolean isgoSetting=false;

    public boolean isNotificationListenerEnabled(Context context) {
        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
        if (packageNames.contains(context.getPackageName())) {
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addCategory(Intent.CATEGORY_HOME);
        startActivity(i);
    }

    private TimeCount timeCount;
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            sendBroadcast(new Intent(MyClearReceiver.ClearKey));
            if (timeCount != null) {
                timeCount.cancel();
            }
            int timeValue=120000;
            if (util.isNotEmpty(ed_clear_time.getText().toString())) {
                timeValue = Integer.valueOf(ed_clear_time.getText().toString()) * 1000;
            }
            timeCount = new TimeCount(timeValue, 1000);
            timeCount.start();
        }
        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }
}
